package net.util;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import net.conf.SystemConf;
import net.vo.DataPacket;

public class SendPath {
    Socket socket = null;

    public SendPath(DataPacket dp) {
        sendpath(dp);
    }

    private void sendpath(DataPacket dp) {
        try {
            socket = new Socket(dp.getIp(), SystemConf.pathPort);
            String path = SystemConf.sendPathList.get(dp.getContent());
            String content = dp.getContent() + "!" + path;

            DataInputStream fromeServer = new DataInputStream(
                    socket.getInputStream());
            BufferedOutputStream toServer = new BufferedOutputStream(
                    socket.getOutputStream());
            ByteArrayInputStream byteIn = new ByteArrayInputStream(
                    content.getBytes());
            
            byte[] bytes = new byte[1024];
            int len;
            while ((len = byteIn.read(bytes)) != -1) {
                toServer.write(bytes, 0, len);
                toServer.flush();
            }

            String id = fromeServer.readUTF();

            new SendFolder(id, dp.getIp());

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
